package nix.dbutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * DbUtils的部分简单实现
 * 
 * @author berry
 * 
 * @param <T>
 */
public class QR<T> {

	private Connection con = null;

	public QR(Connection con) {
		this.con = con;
	}

	/**
	 * 增删改方法
	 * 
	 * @param sql
	 * @param params
	 * @return
	 */
	public int update(String sql, Object... params) {
		PreparedStatement pstmt = null;
		try {
			pstmt = this.con.prepareStatement(sql);
			initParam(pstmt, params);
			return pstmt.executeUpdate();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
			} catch (SQLException e) {
			}
		}
	}

	/**
	 * 查询方法
	 * 
	 * @param sql
	 * @param orh
	 * @param params
	 * @return
	 */
	public T query(String sql, RSHandler<T> rsh, Object... params) {
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			pstmt = this.con.prepareStatement(sql);
			initParam(pstmt, params);
			rs = pstmt.executeQuery();
			return rsh.handler(rs);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (pstmt != null)
					pstmt.close();
				if (rs != null)
					rs.close();
			} catch (SQLException e) {
			}
		}
	}

	/**
	 * 参数赋值
	 * 
	 * @param pstmt
	 * @param params
	 * @throws SQLException
	 */
	private void initParam(PreparedStatement pstmt, Object[] params)
			throws SQLException {
		for (int i = 0; i < params.length; i++) {
			pstmt.setObject(i + 1, params[i]);
		}
	}
}

/**
 * ResultSet ——> JavaBean处理接口（由调用者自己实现）
 * 
 * @author berry
 * 
 * @param <T>
 */
interface RSHandler<T> {
	T handler(ResultSet rs) throws SQLException;
}
